package com.fangzhi.service.impl;

import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.fangzhi.mapper.AdminAccountRoleDeptRelationMapper;
import com.fangzhi.mapper.LogsMapper;
import com.fangzhi.mapper.OrdersMapper;
import com.fangzhi.mobel.AdminAccountRoleDeptRelation;
import com.fangzhi.mobel.Logs;
import com.fangzhi.mobel.OrderAfter;
import com.fangzhi.mobel.Orders;
import com.fangzhi.mobel.enums.GlobalCodeEnum;
import com.fangzhi.mobel.io.SaveAfterOrderIo;
import com.fangzhi.mobel.io.UpdateAfterIo;
import com.fangzhi.mobel.vo.AfterListVo;
import com.fangzhi.mobel.vo.DownloadAfterOrderExcelVo;
import com.fangzhi.mobel.vo.LoginVo;
import com.fangzhi.mobel.vo.PageVo;
import com.fangzhi.service.OrderAfterService;
import com.fangzhi.mapper.OrderAfterMapper;
import com.fangzhi.utils.GlobalParam;
import com.fangzhi.utils.ResponseResult;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.time.LocalDate;
import java.time.format.DateTimeFormatter;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Objects;

/**
* @author edy
* @description 针对表【order_after】的数据库操作Service实现
* @createDate 2024-09-22 22:17:25
*/
@Service
public class OrderAfterServiceImpl extends ServiceImpl<OrderAfterMapper, OrderAfter>
    implements OrderAfterService{

    @Autowired
    private OrdersMapper ordersMapper;
    @Autowired
    private LogsMapper logsMapper;
    @Autowired
    private AdminAccountRoleDeptRelationMapper adminAccountRoleDeptRelationMapper;

    @Override
    public ResponseResult saveAfterOrder(SaveAfterOrderIo io) {
        LoginVo loginVo = GlobalParam.LOGIN_ACCOUNT_INFO.get();
        Orders orders = ordersMapper.selectOne(Wrappers.<Orders>lambdaQuery()
                .eq(Orders::getOrderId, io.getOrderId()));
        if (null == orders)
            return ResponseResult.systemException(GlobalCodeEnum.GL_FAIL_9996);
        if (!Objects.equals(orders.getAdminAccountId(), loginVo.getId()))
            return ResponseResult.systemException(GlobalCodeEnum.GL_FAIL_9997);
        if (orders.getStatus() != 4 && orders.getStatus() != 5)
            return ResponseResult.systemException(GlobalCodeEnum.GL_FAIL_9993);

        BigDecimal price = io.getPrice().multiply(BigDecimal.valueOf(100));
        OrderAfter orderAfter = new OrderAfter().setOrderId(io.getOrderId()).setImageCover(io.getImageCover())
                .setStatus(3).setAdminAccountId(loginVo.getId()).setComments(io.getComments()).setBelongTo(io.getBelongTo())
                .setAction(io.getAction()).setReturnOrderNumber(io.getReturnOrderNumber()).setType(io.getAfterOrderType());


        if(io.getType() == 1){
            orderAfter.setAfterPrice(price.intValue());
        }else{
            orderAfter.setPrice(price.intValue());
        }
        boolean save = this.save(orderAfter);
        if (save){
            if (io.getType() == 1){
                orders.setAfterAmount(orders.getAfterAmount() +  price.intValue());
            }else if (io.getType() == 2){
                orders.setAfterAmount(orders.getAfterAmount() -  price.intValue());
            }
            ordersMapper.updateById(orders);
            logsMapper.insert(new Logs().setType(3).setType2(1).setAboutId(orderAfter.getId()).setAdminAccountId(loginVo.getId()));
            return ResponseResult.OK();
        }
        throw new RuntimeException("添加订单售后异常" + JSON.toJSONString(io));
    }

    @Override
    public ResponseResult toExists(Integer id, Integer needStatus, Long roleId, Integer pass) {
        LoginVo loginVo = GlobalParam.LOGIN_ACCOUNT_INFO.get();
        OrderAfter orderAfter = this.getBaseMapper().selectById(id);
        if (orderAfter.getStatus() != needStatus)
            return ResponseResult.systemException(GlobalCodeEnum.GL_FAIL_9996);

        orderAfter.setStatus(needStatus + 1);
        if (pass == 2)
            orderAfter.setStatus(4);

        boolean b = this.updateById(orderAfter);
        if (b){
            Logs logs = new Logs().setType(1).setType2(2).setAboutId(orderAfter.getId()).setAdminAccountId(loginVo.getId()).setType3(1);
            if (pass ==2)
                logs.setType3(2);
            logsMapper.insert(logs);

            if (roleId == 5L){
                Orders orders = ordersMapper.selectOne(Wrappers.<Orders>lambdaQuery().eq(Orders::getOrderId, orderAfter.getOrderId()));
                orders.setAfterAmount(orders.getAfterAmount() + orderAfter.getPrice());
                if (orders.getTotalAmount() <= (orders.getDepositAmount() + orders.getAfterAmount() + orders.getDiscountAmount()))
                    orders.setStatus(5);
                ordersMapper.updateById(orders);
            }
            return ResponseResult.OK();
        }
        throw new RuntimeException("售后审核失败");
    }

    @Override
    public ResponseResult afterList(String orderId, LocalDate beginTime, LocalDate endTime, LocalDate beginTimeOrder, LocalDate endTimeOrder, String hotelName, Integer pageNo, Integer pageSize) {
        DateTimeFormatter dtf = DateTimeFormatter.ofPattern("yyyy-MM-dd");
        String begin = null;
        String end = null;
        String beginOrder = null;
        String endOrder = null;
        if (null != beginTime && null != endTime){
            begin = beginTime.format(dtf) + " 00:00:00";
            end = endTime.format(dtf) + " 23:59:59";
        }
        if (null != beginTimeOrder && null != endTimeOrder){
            beginOrder = beginTimeOrder.format(dtf) + " 00:00:00";
            endOrder = endTimeOrder.format(dtf) + " 23:59:59";
        }
//        Long total = this.getBaseMapper().selectCount(Wrappers.<OrderAfter>lambdaQuery()
//                        .in(OrderAfter::getStatus, Arrays.asList(2, 3))
//                .ge(null != begin, OrderAfter::getCtime, begin)
//                .le(null != end, OrderAfter::getCtime, end));
        long total = this.getBaseMapper().afterListCount(orderId, begin, end, beginOrder, endOrder, hotelName);
        if (total == 0L)
            return ResponseResult.OK(new PageVo().setTotal(total).setData(new ArrayList<>()));
        List<AfterListVo> voList = this.getBaseMapper().afterList(orderId, begin, end, beginOrder, endOrder,  hotelName, (pageNo - 1) * pageSize, pageSize);
        voList.parallelStream().forEach(T->{
            if (T.getPrice() > 0D){
                T.setPriceType(2);
            }else if (T.getAfterPrice() > 0D) {
                T.setPriceType(1);
            }
        });
        return ResponseResult.OK(new PageVo().setTotal(total).setData(voList));
    }

    @Override
    public ResponseResult updateAfter(UpdateAfterIo io) {
        LoginVo loginVo = GlobalParam.LOGIN_ACCOUNT_INFO.get();
        OrderAfter orderAfter = this.getBaseMapper().selectById(io.getId());
        BigDecimal price = io.getLastPrice().multiply(BigDecimal.valueOf(100));
        orderAfter.setPrice(0).setAfterPrice(0);
        if (io.getPriceType() == 1){
            orderAfter.setAfterPrice(price.intValue());
        }else{
            orderAfter.setPrice(price.intValue());
        }
        orderAfter.setBelongTo(io.getBelongTo()).setAction(io.getAction()).setType(io.getType())
                .setReturnOrderNumber(io.getReturnOrderNumber()).setReturnStatus(io.getReturnStatus())
                .setReturnAdminAccountId(loginVo.getId()).setComments(io.getComments());
        boolean b = this.updateById(orderAfter);
        if (b)
            return ResponseResult.OK();
        throw new RuntimeException("保存跟进失败" + JSON.toJSONString(io));
    }

    @Override
    public List<DownloadAfterOrderExcelVo> queryAfterOrderExcelList(LocalDate startTime, LocalDate endTime, String hotelName) {
        return this.getBaseMapper().queryAfterOrderExcelList(startTime, endTime,hotelName);
    }
}




